<!--
 * @Description：新增、编辑--授权弹窗
 * @author： wlj
 * @date： 2025/10/14 15:21:47
!-->
<template>
  <el-dialog
    v-loading.fullscreen.lock="fullscreenLoading"
    :title="dialogTitle"
    :visible.sync="dialogFormVisible"
    width="75%"
    top="5vh"
    destroy-on-close
    lock-scroll
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <div class="ac-close" @click="handleColse()"><i class="el-icon-circle-close"></i></div>
    <div class="dash-container">
      <div v-if="actStep===1" class="dc-header">
        <div class="dch-title">接口接入注册</div>
        <div class="dch-desc">完成以下步骤，获取API访问凭证并配置算力资源</div>
      </div>
      <div v-if="actStep===2" class="dc-header">
        <div class="dch-title">算力与资源配置</div>
        <div class="dch-desc">配置接入系统的算力参数和资源访问地址</div>
      </div>
      <el-steps :active="actStep">
        <el-step title="系统注册" description=""></el-step>
        <el-step title="调取凭证" description=""></el-step>
        <el-step title="完成(配置算力)" description=""></el-step>
      </el-steps>
      <div v-if="actStep===1" class="box-card">
        <div class="bc-title">系统接入配置 </div>
        <div class="bc-desc">填写接入系统信息，完成注册</div>
        <el-form ref="form" :rules="rules" :model="form" @submit.native.prevent>
          <el-form-item label="授权系统logo" prop="clientLogo">
            <div v-if="form.clientLogo" class="upload-img">
              <el-image :src="getImgUrl(fileImgUrl)" class="ui-image" fit="cover" :preview-src-list="[getImgUrl(fileImgUrl)]"></el-image>
              <i class="el-icon-error ui-icon" @click="delImg()"></i>
            </div>
            <el-upload
              v-else
              ref="upload"
              class="upload-comp"
              :action="actionUploadApi"
              :on-remove="handleRemove"
              :on-change="handleChanged"
              :on-success="handleUploadSuccess"
              :file-list="fileList"
              :multiple="false"
              :headers="{'token': $store.getters.token}"
              :data="{bucket:'lxw',folderPath:''}"
              :limit="1"
            >
              <el-button v-if="fileList.length===0" slot="trigger" class="file-btn" type="primary">选取文件<i class="el-icon-folder-add el-icon--right" /></el-button>
              <span slot="tip" class="el-upload__tip">请上传后缀为 .jpeg .jpg .svg .png 格式的文件</span>
            </el-upload>
          </el-form-item>
          <el-form-item label="授权系统名称" prop="clientName">
            <el-input v-model="form.clientName" placeholder="填写授权系统名称" />
          </el-form-item>
          <el-form-item label="文件API接口" prop="fileApi">
            <el-input v-model="form.fileApi" placeholder="文件API接口" />
          </el-form-item>
          <el-form-item label="文件API请求方法" prop="method">
            <el-select v-model="form.method" placeholder="请选择" class="sel-input-width">
              <el-option label="GET" value="GET" />
              <el-option label="POST" value="POST" />
            </el-select>
          </el-form-item>
          <el-form-item label="系统描述" prop="remark">
            <el-input v-model="form.remark" type="textarea" :autosize="{ minRows:3}" placeholder="选填，描述系统功能和用途"> </el-input>
          </el-form-item>
        </el-form>
        <div class="bc-btn">
          <el-button @click="handleCancel('reset')">重置</el-button>
          <el-button type="primary" @click="handleClientID('form')">保存</el-button>
        </div>
      </div>
      <div v-if="actStep===2">
        <div class="box-card">
          <div class="bc-title">系统接入信息</div>
          <div class="bc-row">
            <div class="bcr-column">
              <el-image :src="getImgUrl(fileImgUrl)" class="bc-img" fit="cover" :preview-src-list="[getImgUrl(fileImgUrl)]"></el-image>
            </div>
            <div class="bcr-column">
              <div class="bcrc-icon">
                <i class="el-icon-film"></i>
              </div>
              <div>
                <div class="bcrc-title">系统名称</div>
                <div>{{ resData.clientName }}</div>
              </div>
            </div>
            <div class="bcr-column">
              <div class="bcrc-icon">
                <i class="el-icon-key"></i>
              </div>
              <div>
                <div class="bcrc-title">Client ID</div>
                <div>{{ resData.clientSecret }}</div>
                <el-button type="text" @click="handleCopyID()">复制ID</el-button>
              </div>
            </div>
          </div>
        </div>
        <el-form ref="hashForm" :rules="hashRules" :model="hashForm" @submit.native.prevent>
          <div class="box-card">
            <div class="bc-title">算力资源配置</div>
            <div class="bc-desc">设置接入系统的算力使用限制</div>
            <el-form-item label="总算力配额" prop="totalQuota">
              <el-input v-model.number="hashForm.totalQuota" type="number" :min="0" step="1" placeholder="系统可使用的总算力额度">
                <template slot="append">Token</template>
              </el-input>
              <div class="bc-tip">1CU=1核CPU+4GB内存的计算能力，可处理约1000次标准API调用 </div>
            </el-form-item>
            <el-form-item label="单日最大算力" prop="maxPower">
              <el-input v-model.number="hashForm.maxPower" type="number" :min="0" placeholder="系统每日可使用的最大算力">
                <template slot="append">CU/天</template>
              </el-input>
            </el-form-item>
            <el-alert title="单日最大算力不应超过总算力配额的30%，以避免短期内资源耗尽 " :closable="false" type="warning" show-icon />
          </div>
          <div class="box-card">
            <div class="bc-title">资源访问配置</div>
            <div class="bc-desc">设置接入系统的资源访问地址</div>
            <el-form-item label="回调通知地址" prop="cbkNotfAds">
              <el-input v-model="hashForm.cbkNotfAds" placeholder="异步任务结果回调地址" />
            </el-form-item>
            <div class="bc-jsb">
              <div class="">ip访问白名单</div>
              <el-button type="text" @click="handleAddIp()">添加Ip</el-button>
            </div>
            <div v-for="(item,i) in hashForm.ipList" :key="i" class="bc-item">
              <el-input v-model="item.url" placeholder="请输入ip地址" />
              <i class="el-icon-delete bci-icon" @click="handleDelete(i)"></i>
            </div>
            <div class="bc-btn">
              <el-button @click="handleCancel('lastStep')">上一步</el-button>
              <el-button type="primary" @click="handleSave('hashForm')">保存配置</el-button>
            </div>
          </div>
        </el-form>
      </div>
      <div v-if="actStep===3" class="box-card">
        <el-result icon="success" title="成功" sub-title="请根据提示进行操作">
          <template slot="extra">
            <el-button type="primary" size="medium" @click="handleCancel('goback')">关闭</el-button>
          </template>
        </el-result>
      </div>
    </div>
  </el-dialog>
</template>
<script>
import store from '@/store'
import { iamAuthRegister, iamAuthEdit } from '@/api/authAPIFun/index'
export default {
  name: '',
  props: {
    disType: {
      type: String,
      default: undefined
    },
    dialogTitle: {
      type: String,
      default: undefined
    },
    editParam: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      fullscreenLoading: false,
      dialogFormVisible: true,
      actStep: 1,
      form: {
        clientId: '',
        clientName: '',
        clientLogo: '',
        fileApi: '',
        method: '',
        remark: ''
      },
      rules: {
        clientName: [{ required: true, message: '请输入授权系统名称', trigger: 'blur' }],
        clientLogo: [{ required: true, message: '请上传授权系统logo', trigger: 'blur' }],
        fileApi: [
          { required: true, message: '请输入文件API接口', trigger: 'blur' }
          // {
          //   pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/,
          //   message: '请输入有效的URL地址格式',
          //   trigger: 'blur'
          // }
        ],
        method: [{ required: true, message: '请选择文件API请求方法', trigger: 'blur' }]
      },
      actionUploadApi: process.env.VUE_APP_BASE_API + '/file2/uploadFile',
      fileList: [],
      fileImgUrl: '',
      resData: {}, // 保存后的数据
      hashForm: {
        totalQuota: '',
        maxPower: '',
        cbkNotfAds: '',
        ipList: []
      },
      hashRules: {
        totalQuota: [
          { required: true, message: '请输入系统可使用的总算力额度', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ],
        maxPower: [
          { required: true, message: '请输入系统每日可使用的最大算力', trigger: 'blur' },
          { type: 'number', message: '请输入有效的数字', trigger: 'blur' }
        ],
        cbkNotfAds: [
          { required: false, message: '请输入异步任务结果回调地址', trigger: 'blur' },
          {
            pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/,
            message: '请输入有效的URL地址格式',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  mounted() {
    if (this.disType === 'edit') {
      this.form = {
        clientId: this.editParam.clientId,
        clientName: this.editParam.clientName,
        clientLogo: this.editParam.clientLogo,
        fileApi: this.editParam.fileApi,
        method: this.editParam.fileApiMethod,
        remark: this.editParam.remark,
        clientSecret: this.editParam.clientSecret
      }
      this.resData = this.form
      this.fileImgUrl = this.editParam.previewFileClientLogo
    }
  },
  methods: {
    // 获取图片路径
    getImgUrl(url) {
      return this.global.baseApi + url + `&token=${store.getters.token}`
    },
    // 删除logo
    delImg() {
      this.form.clientLogo = ''
      this.fileList = []
    },
    // 关闭
    handleColse() {
      this.$emit('event', false)
    },
    // 取消
    handleCancel(type) {
      // 重置
      if (type === 'reset') {
        this.form = {
          clientId: '',
          clientName: '',
          clientLogo: '',
          fileApi: '',
          method: '',
          remark: ''
        }
      }
      // 上一步
      if (type === 'lastStep') {
        this.actStep = 1
      }
      // 返回
      if (type === 'goback') {
        this.handleColse()
        this.actStep = 1
        this.form = {
          code: '',
          name: '',
          description: ''
        }
        this.hashForm = {
          totalQuota: '',
          maxPower: '',
          cbkNotfAds: '',
          ipList: []
        }
      }
    },
    // 选取文件--附件
    handleChanged(file, fileList) {
      const validExtensions = ['.jpeg', '.jpg', '.svg', '.png']
      const fileExtension = file.name.slice((Math.max(0, file.name.lastIndexOf('.')) || Infinity) + 1).toLowerCase()
      if (!validExtensions.includes(`.${fileExtension}`)) {
        this.$message.error('仅支持上传  .jpeg .jpg .svg .png 格式的文件')
        this.fileList = []
        return
      }
      this.fileList = fileList
    },
    // 移除文件
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    // 文件上传成功
    handleUploadSuccess(res, file) {
      if (res.code === 200 && res.success) {
        this.form.clientLogo = res.data.filePath
        this.fileImgUrl = res.data.fileUrl
      } else {
        this.form.clientLogo = ''
        this.fileList = []
        this.fileImgUrl = ''
        // 强制清空上传组件的文件显示
        if (this.$refs.fileUpload) {
          this.$refs.fileUpload.clearFiles()
        }
        this.$message.error(res.message || '文件上传失败，请稍后重试')
      }
    },
    // 保存第一步
    handleClientID(formRef) {
      this.$refs[formRef].validate(v => {
        if (v) {
          if (this.disType === 'add') {
            iamAuthRegister(this.form).then(res => {
              if (res.success) {
                this.resData = res.data
                this.$message.success(res.message || '保存成功')
                this.handleNext(2)
              }
            })
          } else if (this.disType === 'edit') {
            iamAuthEdit(this.form).then(res => {
              if (res.success) {
                this.handleNext(2)
              }
            })
          }
        }
      })
    },
    // 复制内容方法--打包发布后，复制报错修改
    handleCopyID() {
      const textToCopy = this.resData.clientSecret
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(textToCopy).then(() => {
          this.$message({ message: '复制成功', type: 'success' })
        }).catch(() => {
          this.$message({ message: '复制失败', type: 'error' })
        })
      } else {
        // 创建text area
        const textArea = document.createElement('textarea')
        textArea.value = textToCopy
        // 使text area不在viewport，同时设置不可见
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()
        return new Promise((resolve, reject) => {
          // 执行复制命令并移除文本框
          document.execCommand('copy') ? resolve() : reject(new Error('出错了'))
          textArea.remove()
        }).then(() => {
          this.$message({ message: '复制成功', type: 'success' })
        }, () => {
          this.$message({ message: '复制失败', type: 'error' })
        })
      }
    },
    // 下一步
    handleNext(num) {
      this.dialogVisible = false
      this.actStep = parseInt(num)
    },
    // 添加IP
    handleAddIp() {
      this.hashForm.ipList.push({ url: '' })
    },
    handleDelete(index) {
      this.hashForm.ipList.splice(index, 1)
    },
    // 保存配置
    handleSave(formRef) {
      this.$refs[formRef].validate(v => {
        if (v) {
          this.actStep = 3
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep{
  .el-step__head.is-process{
    color: #C0C4CC;
    border-color: #C0C4CC;
  }
  .el-step__title.is-process{
    color: #C0C4CC;
  }
}
.upload-img{
  margin-top: 50px;
  .ui-image{
    width: 80px;
    height: 80px;
  }
  .ui-icon{
    cursor: pointer;
    font-size: 20px;
    color:#f00;
    background: #fff;
    border-radius: 100%;
    position: absolute;
    left:70px;
    top:42px;
  }
}
.upload-comp{
  margin-top: 50px;
  .el-upload__tip{ margin-left: 20px; }
}
.ac-close{
  position: absolute;
  top: 20px;
  right: 30px;
  font-size: 26px;
  cursor: pointer;
  color: #000;
}
.dash-container{
  padding: 0px 50px;
  .dc-header{
    margin-bottom: 30px;
    .dch-title{
      font-size: 24px;
      margin-bottom: 10px;
    }
    .dch-desc{
      font-size: 14px;
      color: #7e8b9e;
    }
  }
  .box-card{
    margin-top: 30px;
    background: #fff;
    border-radius: 10px;
    padding: 30px;
    border:1px solid #e2e2e2;
    .bc-title{
      font-size: 18px;
      margin-bottom: 10px;
    }
    .bc-desc{
      font-size: 14px;
      color: #7e8b9e;
      margin-bottom: 30px;
    }
    .bc-btn{
      margin: 30px 0 10px 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .bc-tip{
      font-size: 14px;
      color: #7e8b9e;
    }
    .bc-row{
      display: grid;
      grid-template-columns: 200px 1fr 1fr 1fr;
      margin-top: 20px;
      .bcr-column{
        display: flex;
        align-items: center;
        font-weight: bold;
         .bc-img{
            width: 80px;
            height: 80px;
            border-radius: 50%;
          }
        .bcrc-icon{
          background: #eff6ff;
          color: #3a72ed;
          border-radius: 100%;
          padding: 10px;
          font-size: 20px;
          margin-right: 15px;
        }
        .bcrc-title{
          font-weight: 400;
          color: #778599;
          margin-bottom: 10px;
        }
      }
    }
    .bc-jsb{
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      color: #606266;
      font-weight: 700;

    }
    .bc-item{
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;
     .bci-icon{
        font-size: 20px;
        margin-left: 10px;
        color: #f00;
        cursor: pointer;
      }
    }
  }
}
</style>

